package com.hrpc.loadbalancer.impl;

import com.hrpc.discovery.Register;
import com.hrpc.exceptions.LoadBalancerException;
import com.hrpc.hRpcBootStarp;
import com.hrpc.loadbalancer.AbstractLoadBalancer;
import com.hrpc.loadbalancer.LoadBalancer;
import com.hrpc.loadbalancer.Selector;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮训的负载均衡策略
 */
public class RoundRobinLoadBalancer extends AbstractLoadBalancer {

    @Override
    protected Selector getSelector(List<InetSocketAddress> serviceList) {
        return new RoundRobinLoadSelector(serviceList);
    }

    private static class RoundRobinLoadSelector implements Selector{
        private List<InetSocketAddress> serviceList;
        //原子Integer
        private AtomicInteger index;

        public RoundRobinLoadSelector(List<InetSocketAddress> serviceList) {
            this.serviceList = serviceList;
            this.index=new AtomicInteger(0);
        }

        @Override
        public InetSocketAddress getNext() {
            if (serviceList==null || serviceList.size()==0){
                throw new LoadBalancerException("拉起的服务列表长度为0！！！");
            }
            InetSocketAddress address=serviceList.get(index.get());
            if (index.get() == serviceList.size()-1){
                //如果到了最后一位，那么重置
                index.set(0);
            }else {
                index.incrementAndGet();
            }
            return address;
        }

    }
}
